Popular Searches
Popular Course Categories
Popular Courses

Creating Lists, Dictionaries, and Sets Using Comprehensions

Creating Lists, Dictionaries, and Sets Using Comprehensions

Python Dictionaries, Sets, and Comprehensions

Creating Lists, Dictionaries, and Sets Using Comprehensions

Course: Python Training

Topic: Creating Lists, Dictionaries, and Sets Using Comprehensions

Course Link: Python Training Course – JustAcademy

Demo Link: Register for a Free Course Demo

Official Website: JustAcademy


1. Introduction to Comprehensions in Python

Comprehensions are a concise and readable way to create new collections in Python using existing iterables such as lists, tuples, strings, ranges, and other collections. They allow developers to apply expressions, loop through items, and filter values without writing multiple lines of traditional loop code.

Python supports three commonly used collection comprehensions:

  • List comprehension: Creates a new list using square brackets.
  • Dictionary comprehension: Creates a dictionary containing key-value pairs.
  • Set comprehension: Creates a set containing unique elements.

Comprehensions are particularly useful for data transformation, filtering records, removing duplicates, generating calculated values, and preparing data for analysis.

2. Learning Objectives

After completing this topic, you will be able to:

  • Understand the purpose and syntax of Python comprehensions.
  • Create lists using expressions and loops.
  • Filter list elements using conditional expressions.
  • Generate dictionaries with calculated keys and values.
  • Create sets and automatically eliminate duplicate values.
  • Use conditional and nested comprehensions.
  • Choose between comprehensions and traditional loops.
  • Identify common comprehension errors and write readable code.

3. What Is a Comprehension?

A comprehension is an expression that builds a collection by iterating over an iterable and evaluating an expression for each item. Optional conditions can be used to include only selected elements.

For example, suppose you want to create a list of squares from the numbers 1 to 5.

Using a Traditional Loop

numbers = [1, 2, 3, 4, 5]
squares = []

for number in numbers:
    squares.append(number ** 2)

print(squares)

Output:

[1, 4, 9, 16, 25]

Using a List Comprehension

numbers = [1, 2, 3, 4, 5]
squares = [number ** 2 for number in numbers]

print(squares)

Output:

[1, 4, 9, 16, 25]

Both examples produce the same result. The comprehension is shorter because the transformation and iteration are expressed together.

4. General Syntax of Comprehensions

4.1 List Comprehension

[expression for item in iterable]

4.2 Dictionary Comprehension

{key_expression: value_expression for item in iterable}

4.3 Set Comprehension

{expression for item in iterable}

4.4 Comprehensions with Conditions

[expression for item in iterable if condition]
{key: value for item in iterable if condition}
{expression for item in iterable if condition}

The expression determines what is stored in the collection. The for clause specifies the source of the items, and the optional if clause filters them.

5. Creating Lists Using List Comprehensions

A list comprehension creates a new list by evaluating an expression for each item in an iterable. The resulting list preserves the order in which qualifying items are processed and can contain duplicate values.

5.1 Creating a List of Squares

squares = [x ** 2 for x in range(1, 6)]
print(squares)

Output:

[1, 4, 9, 16, 25]

Explanation: The range(1, 6) expression generates numbers from 1 through 5. Each number is squared and added to the resulting list.

5.2 Creating a List of Cubes

cubes = [x ** 3 for x in range(1, 6)]
print(cubes)

Output:

[1, 8, 27, 64, 125]

5.3 Converting Strings to Uppercase

names = ["rahul", "priya", "amit", "neha"]
uppercase_names = [name.upper() for name in names]

print(uppercase_names)

Output:

['RAHUL', 'PRIYA', 'AMIT', 'NEHA']

This technique is useful for normalizing names, labels, and text values before comparison or analysis.

5.4 Filtering Even Numbers

numbers = [1, 2, 3, 4, 5, 6, 7, 8]
even_numbers = [number for number in numbers if number % 2 == 0]

print(even_numbers)

Output:

[2, 4, 6, 8]

The condition number % 2 == 0 selects numbers divisible by 2.

5.5 Filtering Odd Numbers

numbers = range(1, 11)
odd_numbers = [number for number in numbers if number % 2 != 0]

print(odd_numbers)

Output:

[1, 3, 5, 7, 9]

5.6 Applying Conditional Expressions

A conditional expression can transform each item differently. Unlike a filtering condition at the end, the conditional expression chooses the value to include in the result.

numbers = [1, 2, 3, 4, 5, 6]
labels = ["Even" if n % 2 == 0 else "Odd" for n in numbers]

print(labels)

Output:

['Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']

Notice the difference between these patterns:

  • [x for x in numbers if x > 3] filters items.
  • ["Large" if x > 3 else "Small" for x in numbers] transforms every item.

5.7 Extracting Words by Length

words = ["python", "is", "easy", "to", "learn"]
long_words = [word for word in words if len(word) > 3]

print(long_words)

Output:

['python', 'easy', 'learn']

6. Creating Dictionaries Using Dictionary Comprehensions

A dictionary comprehension generates key-value pairs in a compact expression. It is useful for creating mappings, calculating values, converting data formats, and filtering dictionary entries.

6.1 Creating a Dictionary of Squares

squares = {x: x ** 2 for x in range(1, 6)}
print(squares)

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Here, each number becomes a key, and its square becomes the corresponding value.

6.2 Creating a Dictionary from Two Lists

names = ["Amit", "Priya", "Rahul"]
scores = [85, 92, 78]

student_scores = {
    name: score
    for name, score in zip(names, scores)
}

print(student_scores)

Output:

{'Amit': 85, 'Priya': 92, 'Rahul': 78}

The zip() function pairs elements from the two iterables. Iteration stops when the shortest iterable is exhausted, so ensure both lists have the expected lengths if every item must be included.

6.3 Transforming Dictionary Values

prices = {
    "Laptop": 50000,
    "Phone": 20000,
    "Tablet": 15000
}

discounted_prices = {
    item: price * 0.90
    for item, price in prices.items()
}

print(discounted_prices)

Output:

{'Laptop': 45000.0, 'Phone': 18000.0, 'Tablet': 13500.0}

This example applies a 10% discount to each price while keeping the original product names as keys.

6.4 Filtering Dictionary Entries

marks = {
    "Amit": 85,
    "Priya": 92,
    "Rahul": 45,
    "Neha": 38
}

passed_students = {
    name: score
    for name, score in marks.items()
    if score >= 40
}

print(passed_students)

Output:

{'Amit': 85, 'Priya': 92, 'Rahul': 45}

The condition keeps only students whose marks are at least 40.

6.5 Reversing Keys and Values

original = {
    "a": 1,
    "b": 2,
    "c": 3
}

reversed_dict = {
    value: key
    for key, value in original.items()
}

print(reversed_dict)

Output:

{1: 'a', 2: 'b', 3: 'c'}

Important: Dictionary keys must be unique. If multiple original keys have the same value, the reversed dictionary will keep only the last key assigned to that value.

6.6 Converting a List into a Dictionary

words = ["apple", "banana", "cherry"]

word_lengths = {
    word: len(word)
    for word in words
}

print(word_lengths)

Output:

{'apple': 5, 'banana': 6, 'cherry': 6}

This approach is useful when each item needs to be associated with a calculated property.

7. Creating Sets Using Set Comprehensions

A set comprehension creates a set using curly braces and an expression. Sets contain unique hashable elements, so repeated results are automatically removed. Unlike lists, sets do not guarantee a particular iteration order.

7.1 Creating a Set of Squares

squares = {x ** 2 for x in range(1, 6)}
print(squares)

Output:**

{1, 4, 9, 16, 25}

The order shown in a set output is illustrative; set order is not guaranteed.

7.2 Removing Duplicate Values

numbers = [1, 2, 2, 3, 4, 4, 5, 5]
unique_numbers = {number for number in numbers}

print(unique_numbers)

Possible Output:

{1, 2, 3, 4, 5}

A set comprehension is useful when duplicate results are not required. If the goal is only to remove duplicates from an existing iterable, set(numbers) is often simpler.

7.3 Creating a Set of Unique First Letters

names = ["Amit", "Anita", "Rahul", "Riya", "Neha"]
first_letters = {name[0] for name in names}

print(first_letters)

Possible Output:

{'A', 'R', 'N'}

Repeated first letters appear only once because a set stores unique elements.

7.4 Filtering Values in a Set Comprehension

numbers = range(1, 11)
even_squares = {
    number ** 2
    for number in numbers
    if number % 2 == 0
}

print(even_squares)

Output:

{64, 4, 100, 16, 36}

The comprehension selects even numbers and stores their squares in a set. The displayed order may vary.

7.5 Extracting Unique Characters

word = "programming"
unique_characters = {character for character in word}

print(unique_characters)

Possible Output:

{'p', 'r', 'o', 'g', 'a', 'm', 'i', 'n'}

Each distinct character appears once. Use a list comprehension instead if the original character order and repeated characters must be preserved.

8. Comparison of List, Dictionary, and Set Comprehensions

Feature List Comprehension Dictionary Comprehension Set Comprehension
Syntax [expression for item in iterable] {key: value for item in iterable} {expression for item in iterable}
Result List Dictionary Set
Duplicates Allowed Keys must be unique Removed automatically
Ordering Preserves generated item order Preserves key insertion order No guaranteed order
Access By index By key By membership or iteration
Typical use Transforming sequences Building mappings Collecting unique values
Example [x * 2 for x in nums] {x: x * 2 for x in nums} {x * 2 for x in nums}

9. Using Multiple Conditions

Comprehensions can include more than one filtering condition. Each condition must be true for the item to be included.

numbers = range(1, 21)

selected = [
    number
    for number in numbers
    if number % 2 == 0
    if number % 3 == 0
]

print(selected)

Output:

[6, 12, 18]

This selects numbers divisible by both 2 and 3. The same logic can be written with a combined condition:

selected = [
    number
    for number in range(1, 21)
    if number % 2 == 0 and number % 3 == 0
]

10. Nested Comprehensions

A nested comprehension uses multiple for clauses to iterate through more than one iterable. It can be useful for combinations, grids, and flattening nested collections, but complex nesting can reduce readability.

10.1 Generating Coordinate Pairs

coordinates = [
    (x, y)
    for x in range(1, 3)
    for y in range(1, 4)
]

print(coordinates)

Output:

[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)]

The outer loop iterates over x. For each value of x, the inner loop iterates over all values of y.

10.2 Flattening a Nested List

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

flattened = [
    value
    for row in matrix
    for value in row
]

print(flattened)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

The comprehension visits each row and then each value inside that row.

10.3 Creating a Dictionary from Nested Data

students = [
    ("Amit", 85),
    ("Priya", 92),
    ("Rahul", 78)
]

student_marks = {
    name: marks
    for name, marks in students
}

print(student_marks)

Output:

{'Amit': 85, 'Priya': 92, 'Rahul': 78}

11. Practical Real-World Examples

11.1 E-Commerce: Filtering Available Products

products = [
    {"name": "Laptop", "price": 55000, "stock": 8},
    {"name": "Mouse", "price": 700, "stock": 0},
    {"name": "Keyboard", "price": 1500, "stock": 12},
    {"name": "Monitor", "price": 12000, "stock": 3}
]

available_products = [
    product["name"]
    for product in products
    if product["stock"] > 0
]

print(available_products)

Output:

['Laptop', 'Keyboard', 'Monitor']

This list comprehension extracts the names of products that are currently in stock.

11.2 Student Management: Creating a Result Dictionary

marks = {
    "Amit": 82,
    "Priya": 91,
    "Rahul": 35,
    "Neha": 67
}

results = {
    name: "Pass" if score >= 40 else "Fail"
    for name, score in marks.items()
}

print(results)

Output:

{'Amit': 'Pass', 'Priya': 'Pass', 'Rahul': 'Fail', 'Neha': 'Pass'}

11.3 Data Cleaning: Normalizing Names

raw_names = [" Amit ", "PRIYA", " rahul", "Neha  "]

clean_names = [
    name.strip().title()
    for name in raw_names
]

print(clean_names)

Output:

['Amit', 'Priya', 'Rahul', 'Neha']

This example removes leading and trailing whitespace and applies title case. Real data-cleaning tasks may need additional handling for missing values and inconsistent formats.

11.4 Analytics: Counting Items with a Dictionary

items = ["apple", "banana", "apple", "orange", "banana", "apple"]

frequency = {
    item: items.count(item)
    for item in set(items)
}

print(frequency)

Possible Output:

{'apple': 3, 'banana': 2, 'orange': 1}

This example is concise but calls count() repeatedly, which can be inefficient for large datasets. For frequency counting, prefer collections.Counter or a single-pass loop.

from collections import Counter

frequency = dict(Counter(items))
print(frequency)

12. Common Mistakes and How to Avoid Them

Mistake Why It Happens Correct Approach
Using parentheses for a list comprehension Parentheses normally create a generator expression. Use square brackets for a list comprehension.
Confusing filtering with transformation An if at the end filters items, while an inline conditional chooses the output value. Use the appropriate syntax for the desired result.
Expecting duplicate values in a set Sets store only unique hashable elements. Use a list if duplicates must be retained.
Using mutable values as set elements Lists and dictionaries are unhashable. Use immutable, hashable values such as strings, numbers, or suitable tuples.
Repeating dictionary keys Later values overwrite earlier values for the same key. Ensure keys are unique or handle collisions intentionally.
Writing deeply nested comprehensions Complex expressions are difficult to read and debug. Use regular loops or helper functions when logic becomes complicated.
Using a variable before it exists The iterable or expression refers to an undefined name. Check variable names and execution order.

13. Comprehensions vs Traditional Loops

Comprehensions are not automatically the best choice for every task. Choose the approach that makes the code easiest to understand and maintain.

Comprehension Example

numbers = [1, 2, 3, 4, 5]
doubled = [number * 2 for number in numbers]

Equivalent Loop

numbers = [1, 2, 3, 4, 5]
doubled = []

for number in numbers:
    doubled.append(number * 2)

Both approaches create the same list. Comprehensions are convenient for straightforward transformations and filtering. Traditional loops are often better when each iteration involves several steps, exception handling, logging, or complex branching.

14. Performance and Best Practices

  • Use comprehensions for simple, clearly expressed transformations and filters.
  • Choose meaningful variable names such as student, price, or number.
  • Use a list when order and duplicate values matter.
  • Use a dictionary when each key should identify a value.
  • Use a set when uniqueness and membership testing are important.
  • Remember that set iteration order is not guaranteed.
  • Avoid expensive function calls inside comprehensions when they can be calculated once outside.
  • Do not use a comprehension only for side effects, such as printing or modifying unrelated objects. A normal loop is clearer.
  • For large datasets, consider memory usage because list, dictionary, and set comprehensions build their resulting collections in memory.
  • Use a generator expression when values should be processed lazily rather than stored all at once.

15. Practice Exercises

Exercise 1: Create a List of Even Numbers

Use a list comprehension to create a list of even numbers from 1 to 20.

Exercise 2: Convert Temperatures

Given temperatures in Celsius, create a list of Fahrenheit values using the formula F = (C * 9/5) + 32.

Exercise 3: Build a Dictionary

Create a dictionary mapping each number from 1 to 5 to its cube.

Exercise 4: Filter Passing Students

Given a dictionary of student marks, create a new dictionary containing only students who scored 50 or above.

Exercise 5: Find Unique Words

Given a list of repeated words, use a set comprehension to create a collection of unique lowercase words.

Exercise 6: Flatten a Matrix

Use a nested list comprehension to convert a two-dimensional list into a single list.

16. Practice Exercise Solutions

Solution 1

even_numbers = [
    number
    for number in range(1, 21)
    if number % 2 == 0
]

print(even_numbers)

Output:

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Solution 2

celsius = [0, 10, 20, 30, 40]
fahrenheit = [(c * 9 / 5) + 32 for c in celsius]

print(fahrenheit)

Output:

[32.0, 50.0, 68.0, 86.0, 104.0]

Solution 3

cubes = {number: number ** 3 for number in range(1, 6)}
print(cubes)

Output:

{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

Solution 4

marks = {
    "Amit": 75,
    "Priya": 88,
    "Rahul": 42,
    "Neha": 56
}

passed = {
    name: score
    for name, score in marks.items()
    if score >= 50
}

print(passed)

Output:

{'Amit': 75, 'Priya': 88, 'Neha': 56}

Solution 5

words = ["Python", "JAVA", "python", "Java", "SQL"]
unique_words = {word.lower() for word in words}

print(unique_words)

Possible Output:

{'python', 'java', 'sql'}

Solution 6

matrix = [[1, 2], [3, 4], [5, 6]]
flattened = [value for row in matrix for value in row]

print(flattened)

Output:

[1, 2, 3, 4, 5, 6]

17. Interview Questions and Answers

Q1. What is a comprehension in Python?

Answer: A comprehension is a concise way to create a collection by evaluating an expression for items from an iterable, optionally applying conditions.

Q2. What are the three main types of collection comprehensions?

Answer: List comprehensions, dictionary comprehensions, and set comprehensions.

Q3. What is the difference between a list comprehension and a set comprehension?

Answer: A list comprehension creates an ordered list and allows duplicates. A set comprehension creates a set of unique hashable elements and does not guarantee iteration order.

Q4. How do you create a dictionary using a comprehension?

Answer: Use curly braces with a key-value expression, such as {x: x * x for x in range(1, 6)}.

Q5. How do you filter values in a comprehension?

Answer: Add an if condition after the iterable, such as [x for x in numbers if x > 10].

Q6. Can a comprehension contain multiple loops?

Answer: Yes. Multiple for clauses can iterate over nested or separate iterables. The order of the clauses determines the iteration order.

Q7. What happens when a dictionary comprehension generates duplicate keys?

Answer: The later value replaces the earlier value associated with the same key.

Q8. Can a set comprehension contain a list as an element?

Answer: No. Lists are mutable and unhashable, so they cannot be stored directly as set elements.

Q9. When should you avoid comprehensions?

Answer: Avoid them when the expression becomes difficult to read or the logic requires many steps, complex branching, or side effects. A traditional loop or helper function may be clearer.

Q10. What is the difference between a list comprehension and a generator expression?

Answer: A list comprehension builds the complete list in memory. A generator expression produces values lazily as they are requested, which can reduce memory use for large sequences.

18. Quick Revision Checklist

  • List comprehensions use square brackets: [expression for item in iterable].
  • Dictionary comprehensions use key-value pairs: {key: value for item in iterable}.
  • Set comprehensions use curly braces: {expression for item in iterable}.
  • Use trailing if clauses to filter items.
  • Use conditional expressions to choose which value is generated.
  • Use zip() to iterate over corresponding elements of multiple iterables.
  • Dictionary keys must be unique; later assignments replace earlier values for duplicate keys.
  • Sets automatically remove duplicate elements and do not guarantee order.
  • Use nested comprehensions carefully and prioritize readability.
  • Choose the collection type based on whether you need ordering, key-value mappings, or uniqueness.

19. Conclusion

List, dictionary, and set comprehensions are essential Python techniques for creating collections efficiently and expressing common data-processing tasks clearly. List comprehensions are ideal for transforming sequences, dictionary comprehensions build useful mappings, and set comprehensions collect unique values. Understanding their syntax, filtering conditions, nested iteration, and limitations will help you write more concise and maintainable Python programs.

For more structured learning and practical Python training, explore the following JustAcademy resources:

whatsapp